package com.tencent.compose.sample.kotlinx

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import coil3.ImageLoader
import coil3.compose.AsyncImage
import coil3.compose.LocalPlatformContext
import coil3.network.ktor3.KtorNetworkFetcherFactory
import coil3.request.crossfade
import coil3.util.DebugLogger
import io.ktor.http.parseUrl
import kotlinx.coroutines.delay
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.format.char
import kotlinx.datetime.toLocalDateTime
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Composable
internal fun KotlinxSample() {

    Column(
        modifier = Modifier.padding(horizontal = 16.dp)
    ) {
        Spacer(Modifier.height(8.dp))

        Datetime()

        Spacer(Modifier.height(8.dp))

        Ktor()
    }

}

@Composable
private fun Datetime() {

    var timeStr by remember { mutableStateOf("") }

    LaunchedEffect(Unit) {
        while (true) {
            val current = Clock.System.now()
            timeStr = LocalDateTime
                .Format {
                    year()
                    char('-')
                    monthNumber()
                    char('-')
                    dayOfMonth()
                    char(' ')
                    hour()
                    char(':')
                    minute()
                    char(':')
                    second()
                }
                .format(current.toLocalDateTime(TimeZone.of("UTC+8")))
//                .format(current.toLocalDateTime(TimeZone.currentSystemDefault()))

            delay(1000L)
        }
    }
    Text("当前时间：$timeStr")
}

@Composable
private fun Ktor() {
    var httpStatus by remember { mutableStateOf("") }
    var imageUrl by remember { mutableStateOf("") }

    LaunchedEffect(Unit) {
        val api = DefaultBingWallpaperApi(ktorClient)

        httpStatus = "Loading"
        val res = api.getBingWallpapers(0, 1)
        httpStatus = Json.Default.encodeToString(res)
        imageUrl = res.images[0].imageUrl
    }

    Text("当前接口状态：$httpStatus")

    if (imageUrl.isNotEmpty()) {

        AsyncImage(
            model = imageUrl,
            contentDescription = "",
            modifier = Modifier.size(300.dp)
        )
    }
}